package jetbrains.buildServer.cuta.logic.sheet;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;



/**
 * Table cell.
 * @author Leonid Bushuev from JetBrains
 */
public class Cell
{
    @NotNull
    public final Column column;

    @NotNull
    public final Row row;


    /**
     * The text will be shown in the cell.
     */
    @NotNull
    private String myText = "";

    /**
     * Style of text in the cell.
     */
    @NotNull
    public final Style style = new Style();


    public Cell(@NotNull Column column, @NotNull Row row)
    {
        this(column, row, "");
    }


    public Cell(@NotNull Column column, @NotNull Row row, @NotNull String text)
    {
        this.column = column;
        this.row = row;
        this.myText = text;
    }


    public String getHtml()
    {
        int length = myText.length();
        if (length == 0)
            return "&nbsp;";

        boolean multi = myText.contains("\n");

        String tag = style.typewriter ? "tt" : multi ? "div" : "span";

        StringBuilder buf = new StringBuilder(length+16);
        buf.append('<').append(tag).append(" class='cell' style=\"");

        if (style.bold) buf.append("font-weight:bold;");
        if (style.italic) buf.append("font-style:italic;");
        if (style.strikedOut) buf.append("text-decoration:line-through;");
        if (style.color != null) buf.append("color:" + style.color + ";");

        buf.append("\">");

        if (multi)
        {
            for (int p1 = 0; p1 < length;)
            {
                int p2 = myText.indexOf('\n', p1);
                if (p2 < 0)
                    p2 = length;
                if (p1 > 0)
                    buf.append("<br/>");
                buf.append(myText.substring(p1,p2));
                p1 = p2+1;
            }
        }
        else
        {
            buf.append(myText);
        }

        buf.append("</").append(tag).append('>');

        return buf.toString();
    }


    public void addText(@Nullable String value)
    {
        if (value == null)
            return;

        if (myText.length() > 0)
            myText += '\n';
        myText += value;
    }


    @NotNull
    public String getText()
    {
        return myText;
    }


    public void setText(@NotNull String text)
    {
        myText = text;
    }


    public void clearText()
    {
        myText = "";
    }


    @Override
    public String toString()
    {
        return myText;
    }
}
